<!--
 * @Author: HeAo
 * @Date: 2021-09-29 09:36:06
 * @LastEditTime: 2021-09-29 10:18:54
 * @LastEditors: HeAo
 * @Description: 
 * @FilePath: \web2103-2105\web2103code\3-1-ES6\day05\3-promise封装.html
 * 别乱动！
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./jquery.js"></script>
  <script>
    window.onload = function () {
      const baseURL = 'http://47.94.46.113:8888'

      function getPromise(url, method) {
        return new Promise(function (resolve, reject) {
          $.ajax({
            url: baseURL + url,
            method,
            success(res) {
              resolve(res)
            },
            error(err) {
              reject(err)
            }
          })
        })
      }

      // 通过工厂函数获取promise实例
      let pro1 = getPromise('/index/category/findAll', 'get')
      let pro2 = getPromise('/index/carousel/findAll', 'get')

      // let pro3 = Promise.all([pro1, pro2])
      // pro3.then(res => {
      //   console.log(res);
      // }).catch(err => {
      //   console.log(err);
      // })

      // let pro3 = Promise.race([pro1, pro2])
      // pro3.then(res => {
      //   console.log(res.data[0]);
      // }).catch(err => {
      //   console.log(err);
      // })

      // let pro3 = Promise.any([pro1, pro2])
      // pro3.then(res => {
      //   console.log(res);
      // }).catch(err => {
      //   console.log(err);
      // })

      // 通过promise实例方法，访问内部的状态
      // pro1.then(res => {
      //   console.log(res);
      // }).catch(err => {
      //   console.log(err);
      // }).finally(() => {
      //   console.log('finally');
      // })

      // pro2.then(res => {
      //   console.log(res);
      // }).catch(err => {
      //   console.log(err);
      // })

      let obj1 = {
        name: 'zhangsan',
        age: 12,
        gender: 'male'
      }
      let obj2 = {
        status: 500,
        message: '操作失败',
        data: null,
        timestamp: new Date().getDate()
      }

      console.log(Promise.resolve(obj1));
      let pro3 = Promise.resolve(obj1)

      pro3.then(res => {
        console.log(res);
      })

      let pro4 = Promise.reject(obj2)
      pro4.catch(err => {
        console.log(err);
      })

    }
  </script>
</head>

<body>

</body>

</html>